package service

import (
	"encoding/json"
	"errors"
	"gitee.com/ling1314/origin-utility/db"
	"gitee.com/ling1314/origin-utility/miao_ser"
	"time"

	"gitee.com/ling1314/origin-utility/model"
	"gitee.com/ling1314/origin-utility/modules/repository"
	log "github.com/sirupsen/logrus"
)

type deviceService struct {
	baseService
}

func (s deviceService) GetListByOrgId(orgID int64) (result interface{}, err error) {

	var (
		li []model.MiaoClient
	)
	if li, err = repository.MiaoTerminalRepository.FindListByOrgID(orgID); err != nil {
		return
	}
	arr := make([]model.DeviceDetail, len(li))
	for i := range li {
		arr[i] = model.DeviceDetail{
			Client:   li[i],
			IsOnline: db.InfoCatchMaoForIdp[li[i].DeviceID].MemoryPer != 0,
		}
	}
	return arr, nil
}

func (s deviceService) SelectLastLog(logType string, deviceId int64) (result interface{}, err error) {
	switch logType {
	case "cpu":
		return repository.IdpLogRepository.FindLastCpu(deviceId)
	case "memory":
		return repository.IdpLogRepository.FindLastMemory(deviceId)
	case "disk":
		return repository.IdpLogRepository.FindLastDisk(deviceId)
	case "appList":
		return repository.IdpLogRepository.FindLastApp(deviceId)
	case "board":
		return repository.IdpLogRepository.FindLastBoard(deviceId)
	case "sysAbstract":
		return repository.IdpLogRepository.FindLastSysAbstract(deviceId)
	case "base":
		if _, ok := db.InfoCatchMaoForIdp[deviceId]; ok {
			result = db.InfoCatchMaoForIdp[deviceId]
		} else {
			err = errors.New("设备不存在")
		}
		return result, err
	default:
		return nil, errors.New("unknown logType ")
	}
}

func (s deviceService) SendInstruct(deviceId int64, code int, body interface{}) (err error) {
	if !miao_ser.IsOnline(deviceId) {
		return errors.New("设备不在线")
	}
	var bs []byte
	if bs, err = json.Marshal(body); err != nil {
		return err
	}
	return miao_ser.SendInstruct(deviceId, model.ClientInstruct{
		Code:      code,
		ServeTime: time.Now().Unix(),
		Body:      string(bs),
	})
}

func (s deviceService) Page(args model.SearchDevice) (result model.PageResult, err error) {
	var (
		li    []model.MiaoClient
		total int64
	)
	li, total, err = repository.MiaoTerminalRepository.FindPage(args.PageInfo, args.Hostname, args.IP)
	if err != nil {
		return
	}
	result.List = li
	result.Total = total
	return
}

func (s deviceService) Detail(id int64, infoType string) (result interface{}, err error) {
	var (
		o model.MiaoClient
	)
	switch infoType {
	case "base":
		o, err = repository.MiaoTerminalRepository.Find(id)
		if err != nil {
			return
		}
		if o.DeviceID == 0 {
			err = errors.New("id not exist")
			return
		}
		return o, nil
	case "baseInfo":
		return s.baseInfo(id)
	default:
		log.Errorf("未知消息类型：%s", infoType)
		return nil, errors.New("未知消息类型")
	}

}

func (s deviceService) baseInfo(id int64) (o model.MiaoClient, err error) {
	o, err = repository.MiaoTerminalRepository.Find(id)
	return o, err
}
